#!/bin/env python
# -*- coding: utf-8 -*-
"""
抖动器工厂类 - 用于创建不同类型的抖动器实例
"""

import taichi as ti
from enum import Enum
from typing import Optional, Union

from .algorithm import FloydDitherer, BayerDitherer, AtkinsonDitherer
from .kernel_cache_manager import enable_kernel_cache


class DitherAlgorithm(Enum):
    """
    抖动算法枚举类。
    """
    FLOYD = "floyd"
    BAYER = "bayer"
    ATKINSON = "atkinson"


class DitherFactory:
    """
    抖动器工厂类，用于创建不同类型的抖动器实例。
    """
    
    @staticmethod
    def create_ditherer(algorithm: Union[str, DitherAlgorithm], 
                        arch = ti.cpu, 
                        use_cache: bool = False,
                        debug: bool = False, 
                        max_value: int = 255):
        """
        创建指定算法的抖动器实例。
        
        :param algorithm: 抖动算法，可以是DitherAlgorithm枚举或字符串
        :param arch: Taichi架构，默认为CPU，可以设置为ti.gpu启用GPU加速
        :param debug: 是否开启调试模式，默认为False
        :param max_value: 像素最大值，默认为255
        :param use_cache: 是否启用内核缓存，默认为False
        :return: 抖动器实例
        :raises ValueError: 当指定的算法不支持时
        """
        # 如果传入的是字符串，转换为枚举
        if isinstance(algorithm, str):
            algorithm = algorithm.lower()
            try:
                algorithm = DitherAlgorithm(algorithm)
            except ValueError:
                valid_algos = [algo.value for algo in DitherAlgorithm]
                raise ValueError(f"不支持的抖动算法: {algorithm}。可用的算法: {valid_algos}")
        
        if use_cache:
            enable_kernel_cache(
                arch=arch,  # 使用GPU后端
                debug=False,
                kernel_profiler=True,
                offline_cache=True  # 启用离线缓存
            )
        
        # 根据算法类型创建相应的抖动器
        if algorithm == DitherAlgorithm.FLOYD:
            return FloydDitherer(arch=arch, debug=debug, max_value=max_value)
        elif algorithm == DitherAlgorithm.BAYER:
            return BayerDitherer(arch=arch, debug=debug, max_value=max_value)
        elif algorithm == DitherAlgorithm.ATKINSON:
            return AtkinsonDitherer(arch=arch, debug=debug, max_value=max_value)
        else:
            valid_algos = [algo.value for algo in DitherAlgorithm]
            raise ValueError(f"不支持的抖动算法: {algorithm}。可用的算法: {valid_algos}") 